package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikeTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constans.RedisConstans;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author slqf
 * @since 2024-03-11
 */
@Service
@RequiredArgsConstructor
public class LikedRecordServiceRedisImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper mqHelper;

    private final StringRedisTemplate redisTemplate;

    @Override
    public void addLikeRecord(LikeRecordFormDTO recordDTO) {
        //基于前端的参数，判断是执行点赞还是取消点赞
        boolean success = recordDTO.getLiked() ? like(recordDTO) : unlike(recordDTO);
        //判断执行是否成功
        if (!success)
            return;

        //如果执行成功，统计点赞数
        Long likeTimes = redisTemplate.opsForSet().size(RedisConstans.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId());
        //缓存点赞数到redis
        if (likeTimes == null) {
            return;
        }

        redisTemplate.opsForZSet().add(
                RedisConstans.LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType(),
                recordDTO.getBizId().toString(),
                likeTimes);
    }

    @Override
    public Set<Long> isBizLikes(List<Long> bizIds) {
        Long userId = UserContext.getUser();
        //查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;

            for (Long bizId : bizIds) {
                String key = RedisConstans.LIKES_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });

        return IntStream.range(0, objects.size())
                .filter(i -> (boolean) objects.get(i))
                .mapToObj(bizIds::get)
                .collect(Collectors.toSet());

    }

    @Override
    public void readTimesAndSendMessage(String bizType, int maxBizSize) {
        //读取并移除redis中缓存的数据
        String key = RedisConstans.LIKES_TIMES_KEY_PREFIX + bizType;
        Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.opsForZSet().popMin(key, maxBizSize);
        if (CollUtils.isEmpty(tuples)) {
            return;
        }
        //数据转换
        List<LikeTimesDTO> list = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> tuple : tuples) {
            String bizId = tuple.getValue();
            Double likeTimes = tuple.getScore();
            if (bizId == null || likeTimes == null)
                continue;
            list.add(LikeTimesDTO.of(Long.valueOf(bizId), likeTimes.intValue()));
            //发送MQ消息
            mqHelper.send(
                    LIKE_RECORD_EXCHANGE,
                    StringUtils.format(LIKED_TIMES_KEY_TEMPLATE , bizType),
                    list);
        }
    }

    private boolean unlike(LikeRecordFormDTO recordDTO) {
        //获取用户ID
        Long user = UserContext.getUser();
        //获取key
        String key = RedisConstans.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId();
        //删除缓存
        Long result = redisTemplate.opsForSet().remove(key, user.toString());

        return result != null && result > 0;

    }

    private boolean like(LikeRecordFormDTO recordDTO) {
        //获取用户ID
        Long user = UserContext.getUser();
        //获取key
        String key = RedisConstans.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId();
        //写入缓存
        Long result = redisTemplate.opsForSet().add(key, user.toString());

        return result != null && result > 0;
    }
}
